package Lotr.game;

import Lotr.game.GUI.MainFrame;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class Game extends Canvas {

    private Timer timer;
    private TimerTask renderTask;
    private GameManager gameManager;

    public Game(int width, int height) throws IOException {
        this.setSize(width, height);
        this.setIgnoreRepaint(true);
        timer = new Timer();
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                switch(keyCode){
                    case KeyEvent.VK_ESCAPE:{
                        System.exit(0);
                        break;
                    }
                    case KeyEvent.VK_1:{
                        gameManager.hotKey1();
                        break;
                    }
                    case KeyEvent.VK_2:{
                        gameManager.hotKey2();
                        break;
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        }); 
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e){
            }
            
            @Override
            public void mouseReleased(MouseEvent e){
                gameManager.mouseReleased();
            }
            
            @Override
            public void mouseClicked(MouseEvent e){
            }
        });
        gameManager = new GameManager(getWidth(), getHeight(), this);
   }
    
    //TODO: remove parameter
    public void start(MainFrame mf) {
        gameManager.setMF(mf);
        createBufferStrategy(2);
        requestFocus();
        if (renderTask != null) {
            renderTask.cancel();
        }
        renderTask = new TimerTask() {

            @Override
            public void run() {
                gameLoop();
            }
        };
        timer.schedule(renderTask, 0, 20);
    }

    private void gameLoop() {
        gameManager.update();
        render();
    }

    private void render() {
        BufferStrategy bf = this.getBufferStrategy();
        Graphics g = null;
        try {
            g = bf.getDrawGraphics();
            g.clearRect(0, 0, getWidth(), getHeight());
            gameManager.render(g);
        } finally {
            g.dispose();
        }
        bf.show();
        Toolkit.getDefaultToolkit().sync();
    }
}
